package org.metasketch.graphics.language.validator;

import java.util.ArrayList;
import java.util.List;

import org.metasketch.graphics.language.xml.CustomStyle;
import org.metasketch.graphics.language.xml.GraphicNotation;
import org.metasketch.graphics.language.xml.NamedEntity;
import org.metasketch.graphics.language.xml.StyleVar;

public class LanguageGraphicsValidator {
	

	public static Messaging validate(GraphicNotation notation) throws Throwable {

		Messaging messaging = new Messaging();

		List<String> registeredNames = new ArrayList<String>();

		List constants = notation.getConstants();
		testRegisteredNames(messaging, registeredNames, constants, null);

		List images = notation.getImages();
		testRegisteredNames(messaging, registeredNames, images, null);

		List styles = notation.getStyles();
		testRegisteredNames(messaging, registeredNames, styles, null);
		
		//a style cannot have a duplicate style var
		for (Object obj : styles) {
			CustomStyle style = (CustomStyle) obj;
			List variables = style.getVariables();
			testRegisteredNames(messaging, new ArrayList<String>(), variables, " in Style '" + style.getName() + "'");
		}

		List slots = notation.getSlots();
		testRegisteredNames(messaging, registeredNames, slots, null);

		List bindings = notation.getBindings();
		testRegisteredNames(messaging, registeredNames, bindings, null);

		
		
		//missing graphics... and child collections...
		
		return messaging;

	}

	private static void testRegisteredNames(Messaging messaging,
			List<String> registeredNames, List<NamedEntity> entities, String option) {
		for (NamedEntity entity : entities) {

			if (entity.getName() == null || entity.getName().length() == 0) {
				messaging.addError("Non existing name for "
						+ entity.getClass().getSimpleName() + (option != null ? option: "") );
				continue;
			}

			if (registeredNames.contains(entity.getName())) {
				messaging.addError("Duplicate name '" + entity.getName()
						+ "' for " + entity.getClass().getSimpleName() + (option != null ? option: ""));
				continue;
			}

			registeredNames.add(entity.getName());

		}
	}

}
